import { IBuildTaskOption, BuildHook, IBuildResult } from '../@types';
import fs from 'fs'
interface IOptions {
    remoteAddress: string;
    enterCocos: string;
    selectTest: string;
    objectTest: {
        number: number;
        string: string;
        boolean: boolean
    },
    arrayTest: [number, string, boolean];
}
function checkPath(path) {
    try {
        const stats = fs.statSync(path);
        if (stats.isDirectory()) {
            return false;
        }
        else if (stats.isFile()) {
            return true;
        }
        else {
            console.log(`${path} 既不是文件也不是文件夹`);
            return false;
            
        }
    }
    catch (err) {
        return false;
        console.error(`无法读取路径 ${path}: ${err}`);
    }
}
const PACKAGE_NAME = 'cocos_build_replace_md5';

interface ITaskOptions extends IBuildTaskOption {
    packages: {
        'cocos-plugin-template': IOptions;
    };
}

function log(...arg: any[]) {
    return console.log(`[${PACKAGE_NAME}] `, ...arg);
}

let allAssets = [];

export const throwError: BuildHook.throwError = true;

export const load: BuildHook.load = async function() {
    console.log(`[${PACKAGE_NAME}] Load cocos plugin example in builder.`);
    allAssets = await Editor.Message.request('asset-db', 'query-assets');
};

export const onBeforeBuild: BuildHook.onBeforeBuild = async function(options: ITaskOptions, result: IBuildResult) {
    // Todo some thing
    log(`${PACKAGE_NAME}.webTestOption`, 'onBeforeBuild');
};

export const onBeforeCompressSettings: BuildHook.onBeforeCompressSettings = async function(options: ITaskOptions, result: IBuildResult) {
    const pkgOptions = options.packages[PACKAGE_NAME];
    if (pkgOptions.webTestOption) {
        console.debug('webTestOption', true);
    }
    // Todo some thing
    console.debug('get settings test', result.settings);
};

export const onAfterCompressSettings: BuildHook.onAfterCompressSettings = async function(options: ITaskOptions, result: IBuildResult) {
    // Todo some thing
    console.log('webTestOption', 'onAfterCompressSettings');
};

export const onAfterBuild: BuildHook.onAfterBuild = async function(options: ITaskOptions, result: IBuildResult) {
    console.log(result, 'result onAfterBuild');
    const getFileame = (path) => {
        let nameArr = path.split('/');
        return nameArr[nameArr.length - 1];
    };
    let Config = {
        'application.js': result.paths.applicationJS,
        'system.bundle.js': result.paths.systemJs,
        'polyfills.bundle.js': result.paths.polyfillsJs,
        'style.css': result.paths.styleCSS,
        'import-map.json': result.paths.importMap,
        'settings.json': result.paths.settings,
    };
    //内容审查
    for (const key in result.paths) {
        let path = result.paths[key];
        if (typeof path === 'object') {
            continue;
        }
        if (checkPath(path)) {
            try {
                const content = fs.readFileSync(path, 'utf8');
                let newContent = content;
                for (const [key, value] of Object.entries(Config)) {
                    const regex = new RegExp(key, 'g');
                    newContent = newContent.replace(regex, getFileame(value));
                }
                //返回新内容
                fs.writeFileSync(path, newContent);
            } catch (error) {
                    console.error(`${path} 写入/读取失败: ${error}`);
            }
        }
        else {
            console.log(`${path} is not a file`);
        }
    }
};

export const unload: BuildHook.unload = async function() {
    console.log(`[${PACKAGE_NAME}] Unload cocos plugin example in builder.`);
};

export const onError: BuildHook.onError = async function(options, result) {
    // Todo some thing
    console.warn(`${PACKAGE_NAME} run onError`);
};

export const onBeforeMake: BuildHook.onBeforeMake = async function(root, options) {
    console.log(`onBeforeMake: root: ${root}, options: ${options}`);
};

export const onAfterMake: BuildHook.onAfterMake = async function(root, options) {
    console.log(`onAfterMake: root: ${root}, options: ${options}`);
};
